import ctypes
import struct

# 定义 TDevBase 结构体
class TDevBase:
    def __init__(self, year=0, month=0, day=0, no=0):
        self.Year = year
        self.Month = month
        self.Day = day
        self.No = no

    def pack(self):
        # 将 TDevBase 实例打包为二进制数据
        return struct.pack("<HBBI", self.Year, self.Month, self.Day, self.No)

    @classmethod
    def unpack(cls, data):
        # 将二进制数据解包为 TDevBase 实例
        year, month, day, no = struct.unpack("<HBBI", data)
        return cls(year, month, day, no)

# 加载 DLL 并定义函数原型
dll = ctypes.CDLL('./img/generateID.dll')
dll.IDToDevBase_10U.argtypes = [ctypes.c_uint, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]
dll.IDToDevBase_10U.restype = ctypes.c_int

def get_dev_base_info(aid):
    # 创建 TDevBase 实例并调用函数
    dev_base = TDevBase()
    is_new_2021 = ctypes.c_int(0)

    # 将 TDevBase 实例打包为二进制数据
    dev_base_data = dev_base.pack()

    # 调用 C 函数并传递二进制数据
    result = dll.IDToDevBase_10U(aid, ctypes.cast(dev_base_data, ctypes.c_void_p), ctypes.byref(is_new_2021))

    # 检查返回值和结果
    if result == 0:
        # 解包二进制数据为 TDevBase 实例
        dev_base = TDevBase.unpack(dev_base_data)
        return dev_base
    else:
        return None

# # 调用接口函数并打印设备序号信息
# aid = 64310002
# dev_base_info = get_dev_base_info(aid)
# if dev_base_info:
#     print(f"设备序号信息：{dev_base_info.Year}年{dev_base_info.Month}月{dev_base_info.Day}日，序号为 {dev_base_info.No}")
# else:
#     print("调用失败")
